package gov.pbc.nn.kjgl.archive.dao;

import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.kjgl.entity.Archives;
import gov.pbc.nn.kjgl.entity.ArchivesContent;
import gov.pbc.nn.kjgl.entity.ArchivesMember;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.dorado.data.provider.Criteria;
import com.bstek.dorado.data.provider.Page;

@Repository
public class ArchivesInputDao extends AbstractHibernateDao {

	/**
	 * 得到父级的集合，因为可能存在相同的父类，并删除相同的父类
	 * 
	 * @return List<Archives>
	 */
	public List<Archives> getArchives() {
		// String hql =
		// "from Archives where invalid=false and parentId is null and id in
		// (select archivesId from ArchivesMember where type=2 and
		// memberId=:memberId)";
		// Map<String, Object> map = new HashMap<String, Object>();
		// map.put("memberId", ContextHolder.getLoginUserName());
		// List<Archives> ls = this.query(hql, map);
		// if (ls != null) {
		// return ls;
		// }
		// return null;
		List<Archives> resutls = new ArrayList<Archives>();
		String hql = "from Archives where invalid=false and id in (select archivesId from  ArchivesMember where  type=2 and invalid=false and memberId=:memberId)";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("memberId", ContextHolder.getLoginUserName());
		List<String> isExits = new ArrayList<String>();
		List<Archives> ls = this.query(hql, map);
		for (Archives archive : ls) {
			if (StringUtils.isNotEmpty(archive.getParentId())) {
				if (!isExits.contains(archive.getParentId())) {
					resutls.add(getArchivesById(archive.getParentId()));
					isExits.add(archive.getParentId());
				}
			} else {
				resutls.add(archive);
				isExits.add(archive.getId());
			}
		}
		return resutls;

	}

	/**
	 * 根据父类的id，查出来子类的集合
	 * 
	 * @param parentId
	 * @return
	 */
	public List<Archives> getArchivesByParentId(String parentId) {
		// String hql =
		// "from Archives where parentId=:parentId and invalid=false and
		// id=(select archivesId from ArchivesMember where memberId=:memberId)";
		String hql = "from Archives where parentId=:parentId and invalid=false and id in (select archivesId from  ArchivesMember where type=2  and invalid=false and  memberId=:memberId)";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("parentId", parentId);
		map.put("memberId", ContextHolder.getLoginUserName());
		List<Archives> ls = this.query(hql, map);
		if (ls != null) {
			return ls;
		}
		return null;
	}

	/**
	 * 根据id查询出来该类
	 * 
	 * @param id
	 * @return
	 */
	public Archives getArchivesById(String id) {
		String hql = "from Archives where invalid=false and id=:id";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		return (Archives) this.query(hql, map).get(0);

	}

	// public List<ArchivesContent> getArchiveContentByArchivesId(String
	// archivesId) {
	// String hql =
	// "from ArchivesContent where invalid=false and archivesId=:archivesId";
	// Map<String, Object> map = new HashMap<String, Object>();
	// map.put("archivesId", archivesId);
	// return this.query(hql, map);
	// }
	/**
	 * 
	 * 分页查询，并且根据参数进行查询
	 * 
	 * @param page
	 * @param archivesId
	 */
	public void getArchiveContentByArchivesId(Page<ArchivesContent> page, Criteria criteria, String archivesId) {
		DetachedCriteria query = this.buildDetachedCriteria(criteria, ArchivesContent.class);
		query.add(Restrictions.or(Restrictions.eq("invalid", false), Restrictions.isNull("invalid")));
		query.add(Restrictions.eq("archivesId", archivesId));
		this.pagingQuery(page, query);
	}

	/**
	 * 保存档案内容的实体
	 * 
	 * @param archivesId
	 * @param contentFileName
	 * @param pathId
	 */
	public void saveArchivesContent(String archivesId, String contentFileName, Path path) {
		ArchivesContent entity = new ArchivesContent();
		entity.setArchivesId(archivesId);
		entity.setContentFileId(contentFileName);
		entity.setPathId(path.toString());
		entity.setInputUser(ContextHolder.getLoginUserName());
		entity.setInputUsername(ContextHolder.getLoginUser().getCname());
		entity.setDeptId(ContextHolder.getLoginUser().getDepts().get(0).getId());
		entity.setDeptName(ContextHolder.getLoginUser().getDepts().get(0).getName());
		this.save(entity);
	}

	public void delArchivesContent(ArchivesContent ac) throws IOException {
		Path path = Paths.get(ac.getPathId());

		this.delete(ac);
		Files.deleteIfExists(path);
	}

	/**
	 * 根据档案内容的id，对该类进行删除
	 * 
	 * @param archivescontentid
	 * @throws IOException
	 */
	public void delArchivesContent(String archivescontentid) throws IOException {
		String hql = "from ArchivesContent where  invalid=false and id=:id";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", archivescontentid);
		List<ArchivesContent> list = this.query(hql, map);
		ArchivesContent ac = list.get(0);
		this.delArchivesContent(ac);
	}

	/**
	 * 移动之后 修改ArchivesContent信息
	 * 
	 * @param id
	 * @param arid
	 * @throws IOException
	 */
	public void updateContent(String id, String arid) throws IOException {
		String hql = "from ArchivesContent where  invalid=false and id=:id";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", id);
		List<ArchivesContent> list = this.query(hql, map);
		if (list.size() > 0) {
			for (ArchivesContent archivesContent : list) {
				archivesContent.setArchivesId(arid);
				archivesContent.setInputUser(ContextHolder.getLoginUserName());
				archivesContent.setInputUsername(ContextHolder.getLoginUser().getCname());
				archivesContent.setDeptId(ContextHolder.getLoginUser().getDepts().get(0).getId());
				this.update(archivesContent);
			}
		}
	}

	/**
	 * 根据档案类的类型和id，判断该类是否已经存在，存在就返回true
	 * 
	 * @param archivescontentid
	 * @param type
	 * @return
	 */
	public boolean checkArchivesContent(String archivescontentid, int type) {
		// select archivesId from ArchivesMember where type=2 and invalid=false
		// and memberId=:memberId
		String hql = "select count(*) from ArchivesMember where type=:type and invalid =false and  archivesId=:archivesId and memberId=:memberId";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("archivesId", archivescontentid);
		map.put("type", type);
		map.put("memberId", ContextHolder.getLoginUserName());
		int count = this.queryForInt(hql, map);
		if (count > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据档案内容名字检查档案是否已经存在，存在就返回false
	 * 
	 * @param filename
	 * @return
	 */
	public synchronized boolean check(String filename, String archivesId) {
		String hql = "select COUNT(*) from ArchivesContent where invalid=false and contentFileId=:contentFileId and archivesId=:archivesId ";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("contentFileId", filename);
		map.put("archivesId", archivesId);
		int count = this.queryForInt(hql, map);
		if (count == 0) {
			return true;
		} else {
			return false;
		}
	}

	// /**
	// * 传入档案的文件夹名字，返回文档的路径名字
	// *
	// * @param upload
	// * @return
	// */
	// public String getDestPath(String upload) {
	// return System.getProperty("java.io.tmpdir") + upload + File.separator;
	// }
	//
	// /**
	// * 传入档案的文件夹名字，返回文档的路径名字
	// *
	// * @param diry
	// * @return
	// */
	// public String getDiryPath(String diry) {
	// return System.getProperty("java.io.tmpdir") + diry + File.separator;
	// }

	// /**
	// * 根据档案id得到档案的路径
	// *
	// * @param archivescontentid
	// * @return
	// */
	// public String getFilePathByInvesId(String archivescontentid) {
	// String hql = "from ArchivesContent where invalid=false and id=:id";
	// Map<String, Object> map = new HashMap<String, Object>();
	// map.put("id", archivescontentid);
	// List<ArchivesContent> list = this.query(hql, map);
	// ArchivesContent ac = list.get(0);
	// return ac.getPathId();
	// }
	//
	// /**
	// * 得到文件
	// *
	// * @param fileName
	// * @param folder
	// * @return
	// */
	// public File getDestFile(String fileName, File folder) {
	//
	// File destFile;
	//
	// // 若文件不存在直接返回
	// if (!new File(folder, fileName).exists()) {
	// destFile = new File(folder, fileName);
	// } else {
	// int i = 1, lastDotPos = fileName.lastIndexOf("."), len = fileName
	// .length();
	//
	// String prefix = null, suffix = null, destFileName;
	//
	// // 文件名中不存在"."或者最后一位是"."的时候
	// if (lastDotPos == len - 1 || lastDotPos == -1) {
	// prefix = fileName;
	// suffix = "";
	// } else if (lastDotPos != -1) {
	// prefix = fileName.substring(0, lastDotPos);
	// suffix = fileName.substring(lastDotPos + 1);
	// }
	// do {
	// if (suffix.length() == 0) {
	// destFileName = String.format("%s_%d", prefix, i++);
	// } else {
	// destFileName = String.format("%s_%d.%s", prefix, i++,
	// suffix);
	// }
	// destFile = new File(folder, destFileName);
	// } while (destFile.exists());
	//
	// }
	//
	// FileUtils.createDirectory(destFile.getParent());
	//
	// return destFile;
	// }
}
